// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace SnapObjects.Data
{
    internal class JNodeWriter : INodeWriter
    {
        private readonly JsonWriter _writer;
        private readonly StringBuilder _builder;

        public JNodeWriter()
        {
            _writer = new JsonTextWriter(new StringWriter(_builder = new StringBuilder()));
        }

        public INodeWriter WriteAsArray(string name)
        {
            this.WritePropertyName(name);

            _writer.WriteStartArray();

            return this;
        }

        public INodeWriter WriteAsObject(string name)
        {
            this.WritePropertyName(name);

            _writer.WriteStartObject();

            return this;
        }

        public INodeWriter WriteAsValue(string name)
        {
            this.WritePropertyName(name);

            return this;
        }

        public void WriteEndArray()
        {
            _writer.WriteEndArray();
        }

        public void WriteEndObject()
        {
            _writer.WriteEndObject();
        }

        public void WriteNull()
        {
            _writer.WriteNull();
        }

        public void WriteRawValue(string raw)
        {
            _writer.WriteRawValue(raw);
        }

        public void WriteValue(object value)
        {
            _writer.WriteValue(value);
        }

        public override string ToString()
        {
            return _builder.ToString();
        }

        private void WritePropertyName(string name)
        {
            if (_writer.WriteState == WriteState.Array ||
                _writer.WriteState == WriteState.Start)
            {
                return;
            }

            _writer.WritePropertyName(name);
        }
    }
}
